import React, { useState, useRef, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { format } from 'date-fns';
import { Toast } from 'antd-mobile';
import { useAppDispatch, useAppSelector } from '../../../store';
import { 
  getKnowledgeBase, 
  getKnowledgeBaseListByID, 
  publishSickCircle, 
  uploadSickCirclePicture,
  clearDiseaseList,
  clearError
} from '../../../store/sliceReducer/PatientCircleSliceReducer';
import type { 
  PatientCircleFormData, 
  KnowledgeBaseItem, 
  DiseaseListItem 
} from '../../../type/store';
import TopNav from '../../../components/topNav';
import './index.scss';

const BpatientCircleWrite: React.FC = React.memo(() => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  
  // 从 Redux store 获取状态
  const { 
    knowledgeBaseList, 
    diseaseList, 
    status, 
    error, 
    publishResult,
    uploadStatus,
    uploadError 
  } = useAppSelector(state => state.patientCircle);
  
  // 表单数据引用
  const formDataRef = useRef<PatientCircleFormData>({
    title: '',
    departmentId: null,
    disease: '',
    detail: '',
    treatmentHospital: '',
    treatmentStartTime: '',
    treatmentEndTime: '',
    treatmentProcess: '',
    amount: 0
  });
  
  // 本地状态
  const [administrativeOpen, setAdministrativeOpen] = useState(false);
  const [diseaseOpen, setDiseaseOpen] = useState(false);
  const [datePickerOpen, setDatePickerOpen] = useState(false);
  const [isStartTime, setIsStartTime] = useState(true);
  const [rewardOpen, setRewardOpen] = useState(true);
  const [selectedDepartment, setSelectedDepartment] = useState('');
  const [selectedDisease, setSelectedDisease] = useState('');
  const [startTime, setStartTime] = useState('');
  const [endTime, setEndTime] = useState('');
  const [imageList, setImageList] = useState<string[]>([]);
  const [fileList, setFileList] = useState<File[]>([]);
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [customAmount, setCustomAmount] = useState<number | null>(null);
  
  // 文件输入引用
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // 悬赏金额选项
  const rewardAmounts = useMemo(() => [10, 20, 30, null], []);
  
  // 初始化科室数据
  React.useEffect(() => {
    dispatch(getKnowledgeBase());
  }, [dispatch]);
  
  // 处理图片上传
  const handleImageUpload = useCallback(async (sickCircleId: number) => {
    try {
      await Promise.all(
        fileList.map(file => 
          dispatch(uploadSickCirclePicture({ sickCircleId, picture: file }))
        )
      );
      
      Toast.show({
        content: '图片上传成功！',
        icon: 'success',
        duration: 1500,
      });
      
      // 延迟跳转，让用户看到上传成功提示
      setTimeout(() => {
        navigate(-1);
      }, 1000);
    } catch (error) {
      console.error('图片上传失败:', error);
      Toast.show({
        content: '图片上传失败，请重试',
        icon: 'fail',
        duration: 2000,
      });
    }
  }, [fileList, dispatch, navigate]);
  
  // 清空错误信息
  React.useEffect(() => {
    if (error) {
      Toast.show({
        content: error,
        icon: 'fail',
        duration: 3000,
      });
      dispatch(clearError());
    }
  }, [error, dispatch]);
  
  // 处理发布成功
  React.useEffect(() => {
    if (publishResult?.result) {
      Toast.show({
        content: '发布成功！',
        icon: 'success',
        duration: 2000,
      });
      
      // 如果有图片需要上传
      if (fileList.length > 0) {
        handleImageUpload(publishResult.result);
      } else {
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          navigate(-1);
        }, 1500);
      }
    }
  }, [publishResult, fileList, navigate, handleImageUpload]);
  
  // 选择科室
  const handleSelectDepartment = useCallback((item: KnowledgeBaseItem) => {
    setAdministrativeOpen(false);
    setSelectedDepartment(item.departmentName);
    formDataRef.current.departmentId = item.id;
    
    // 获取病症列表
    dispatch(getKnowledgeBaseListByID(item.id));
    setDiseaseOpen(true);
  }, [dispatch]);
  
  // 选择病症
  const handleSelectDisease = useCallback((item: DiseaseListItem) => {
    setDiseaseOpen(false);
    setSelectedDisease(item.name);
    formDataRef.current.disease = item.name;
  }, []);
  
  // 文件转base64
  const fileToBase64 = useCallback((file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }, []);
  
  // 处理文件上传
  const handleFileChange = useCallback(() => {
    const input = fileInputRef.current;
    if (!input?.files) return;
    
    const files = Array.from(input.files);
    
    // 检查图片数量限制
    if (files.length + imageList.length > 6) {
      alert('图片不能超过6张');
      return;
    }
    
    setFileList(prev => [...prev, ...files]);
    
    // 转换为base64预览
    Promise.all(files.map(file => fileToBase64(file)))
      .then(base64List => {
        setImageList(prev => [...prev, ...base64List as string[]]);
      });
  }, [imageList.length, fileToBase64]);
  
  // 处理时间选择
  const handleTimeSelect = useCallback((date: Date) => {
    const formattedDate = format(date, 'yyyy-MM-dd');
    
    if (isStartTime) {
      setStartTime(formattedDate);
      formDataRef.current.treatmentStartTime = formattedDate;
    } else {
      setEndTime(formattedDate);
      formDataRef.current.treatmentEndTime = formattedDate;
    }
    
    setDatePickerOpen(false);
  }, [isStartTime]);
  
  // 处理悬赏金额选择
  const handleAmountSelect = useCallback((amount: number | null, index: number) => {
    setSelectedAmount(index);
    formDataRef.current.amount = amount;
  }, []);
  
  // 处理自定义金额
  const handleCustomAmount = useCallback((value: string) => {
    const numValue = Number(value);
    setCustomAmount(numValue);
    formDataRef.current.amount = numValue;
  }, []);
  
  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    try {
      Toast.show({
        content: '正在发布...',
        icon: 'loading',
        duration: 0, // 不自动关闭
      });
      
      await dispatch(publishSickCircle(formDataRef.current));
      
      // 发布成功后Toast会在useEffect中显示，这里先关闭loading
      Toast.clear();
    } catch (error) {
      console.error('发布失败:', error);
      Toast.clear();
      Toast.show({
        content: '发布失败，请重试',
        icon: 'fail',
        duration: 2000,
      });
    }
  }, [dispatch]);
  
  // 去充值
  const handleRecharge = useCallback(() => {
    navigate('/wallet/recharge');
  }, [navigate]);
  
  return (
    <div className="patient-circle-write">
      {/* 顶部导航栏 */}
      <TopNav title="发布病友圈" />
      
      {/* 内容区域 */}
      <div className="content" style={{ padding: '20px' }}>
        {/* 标题输入 */}
        <div className="title-section">
        <div className="title-input">
          <input 
            type="text" 
            placeholder="请输入标题(最多20个字)" 
            onChange={(e) => {
              formDataRef.current.title = e.target.value;
            }} 
          />
        </div>
      </div>
      
      {/* 科室选择 */}
      <div className="department-section">
        <div className="department-selector" onClick={() => setAdministrativeOpen(true)}>
          <p className="selector-text">
            {selectedDepartment || '请选择就诊科室'}
          </p>
          <span className="arrow">▼</span>
        </div>
        
        {administrativeOpen && (
          <div className="dropdown-menu">
            {knowledgeBaseList.map((item) => (
              <div 
                key={item.id} 
                className="dropdown-item"
                onClick={() => handleSelectDepartment(item)}
              >
                {item.departmentName}
              </div>
            ))}
          </div>
        )}
      </div>
      
      {/* 病症选择 */}
      <div className="disease-section">
        <div className="disease-selector" onClick={() => setDiseaseOpen(true)}>
          <p className="selector-text">
            {selectedDisease || '请选择主要病症'}
          </p>
          <span className="arrow">▼</span>
        </div>
        
        {diseaseOpen && (
          <div className="dropdown-menu">
            {diseaseList.map((item) => (
              <div 
                key={item.id} 
                className="dropdown-item"
                onClick={() => handleSelectDisease(item)}
              >
                {item.name}
              </div>
            ))}
          </div>
        )}
      </div>
      
      {/* 病症详情 */}
      <div className="detail-section">
        <textarea 
          placeholder="请输入病症详情" 
          rows={6}
          onChange={(e) => {
            formDataRef.current.detail = e.target.value;
          }}
        />
        <p className="hint">不超过300字</p>
      </div>
      
      {/* 治疗经历 */}
      <div className="treatment-section">
        <div className="treatment-header">
          <p>请输入最近一段治疗经历</p>
        </div>
        
        <div className="treatment-content">
          {/* 医院名称 */}
          <input 
            type="text" 
            placeholder="请输入医院名称" 
            onChange={(e) => {
              formDataRef.current.treatmentHospital = e.target.value;
            }}
          />
          
          {/* 开始时间 */}
          <div 
            className="time-selector"
            onClick={() => {
              setIsStartTime(true);
              setDatePickerOpen(true);
            }}
          >
            <p className="selector-text">
              {startTime || '请选择开始时间'}
            </p>
            <span className="arrow">▼</span>
          </div>
          
          {/* 结束时间 */}
          <div 
            className="time-selector"
            onClick={() => {
              setIsStartTime(false);
              setDatePickerOpen(true);
            }}
          >
            <p className="selector-text">
              {endTime || '请选择结束时间'}
            </p>
            <span className="arrow">▼</span>
          </div>
          
          {/* 治疗过程 */}
          <textarea 
            placeholder="请输入治疗过程" 
            rows={4}
            onChange={(e) => {
              formDataRef.current.treatmentProcess = e.target.value;
            }}
          />
        </div>
      </div>
      
      {/* 图片上传 */}
      <div className="image-section">
        <p className="hint">最多可添加6张图片；长按为图片排序</p>
        
        <div className="image-upload">
          <div className="image-list">
            {imageList.map((image, index) => (
              <img key={index} src={image} alt={`上传图片${index + 1}`} />
            ))}
            
            <input 
              type="file" 
              accept="image/*" 
              multiple 
              ref={fileInputRef}
              style={{ display: 'none' }}
              onChange={handleFileChange}
            />
            
            <div 
              className="upload-btn"
              onClick={() => fileInputRef.current?.click()}
            >
              <span>+</span>
            </div>
          </div>
        </div>
      </div>
      
      {/* 悬赏设置 */}
      <div className="reward-section">
        <div className="reward-header">
          <p>提示悬赏额度</p>
          <input 
            type="checkbox" 
            checked={rewardOpen}
            onChange={(e) => {
              setRewardOpen(e.target.checked);
              if (!e.target.checked) {
                formDataRef.current.amount = 0;
              }
            }}
          />
        </div>
        
        {rewardOpen && (
          <div className="reward-content">
            <p>提升额度可获得更多的关注,得到更多建议</p>
            
            <div className="amount-options">
              {rewardAmounts.map((amount, index) => (
                <div key={index}>
                  {amount ? (
                    <button 
                      className={`amount-btn ${selectedAmount === index ? 'active' : ''}`}
                      onClick={() => handleAmountSelect(amount, index)}
                    >
                      {amount}H币
                    </button>
                  ) : (
                    <input 
                      type="text" 
                      placeholder="自定义H币"
                      className={`custom-input ${selectedAmount === index ? 'active' : ''}`}
                      onChange={(e) => handleCustomAmount(e.target.value)}
                      onClick={() => setSelectedAmount(index)}
                    />
                  )}
                </div>
              ))}
            </div>
            
            <p className="balance-hint">
              当前H币余额300.不足？去
              <span onClick={handleRecharge}>充值</span>
            </p>
          </div>
        )}
      </div>
      
      {/* 发布按钮 */}
      <button 
        className="submit-btn"
        onClick={handleSubmit}
        disabled={status === 'loading'}
      >
        {status === 'loading' ? '发布中...' : '发布'}
      </button>
      
      {/* 日期选择器 */}
      {datePickerOpen && (
        <div className="date-picker-overlay">
          <div className="date-picker">
            <h3>选择年月日</h3>
            <input 
              type="date" 
              min="2020-01-01"
              max="2025-12-31"
              onChange={(e) => handleTimeSelect(new Date(e.target.value))}
            />
            <div className="picker-actions">
              <button onClick={() => setDatePickerOpen(false)}>取消</button>
              <button onClick={() => setDatePickerOpen(false)}>确定</button>
            </div>
          </div>
        </div>
      )}
      </div>
    </div>
  );
});

export default BpatientCircleWrite;